﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using DunSilverlight.Web.Comm;
using DunLibrary.Organization;
using NHibernate;
using System.ServiceModel.Activation;
using Newtonsoft.Json;
using DunSilverlight.Web.Serializable;
using System.IO;
using DunLibrary.User;

namespace DunSilverlight.Web.OrganizationWcf
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“OrganizationService”。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class OrganizationService : BaseService<Organization>, IOrganizationService
    {
        public string GetMenuTree()
        {
            using (ISession session = SessionFactory.Session)
            {
                //因为ilist不能序列化，所以这样实现
                var obj = session.CreateQuery("from Organization o where o.Parent.Id is null").UniqueResult<Organization>();
                if (obj == null)
                {
                    return this.PackJsonResult("false",JsonConvert.Null, string.Empty);
                }
                var root = new Organization { Id = obj.Id, Name = obj.Name };
                initChildren(session,root);

                using (StringWriter sw = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
                {
                    JsonSerializer serializer = new JsonSerializer
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    };

                    using (JsonWriter jw = new JsonTextWriter(sw))
                    {
                        jw.Formatting = Formatting.Indented;

                        serializer.Serialize(jw, root);
                    }
                    return PackJsonResult("true", sw.ToString(), string.Empty);
                }
            }
        }

        private void initChildren(ISession session,IOrganization obj)
        {
            var list= session.CreateQuery("from Organization o where o.Parent.Id=" + obj.Id).List<Organization>();
            obj.Childs = new List<Organization>();
            foreach (var i in list)
            {
                var item = new Organization { Id = i.Id, Name = i.Name };
                initChildren(session, item);
                obj.Childs.Add(item);
            }
        }

        public string GetUsers(int orgId)
        {
            using (ISession session = SessionFactory.Session)
            {
                var list = session.CreateQuery("from User u where u.Name != 'admin' and u.Organization.Id=" + orgId).List<User>();

                string s = JsonSerializerHelper.EntityToJson(list);

                return PackJsonResult("true", s, string.Empty);
            }
        }

        public override string GetById(int id)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    Organization entity = sess.Get<Organization>(id);

                    bool b1 = NHibernateUtil.IsInitialized(entity.Parent);

                    bool b2 = NHibernateUtil.IsInitialized(entity.Childs);

                    //Newtonsoft.Json.JsonConverter j = null;
                    

                    string s = JsonSerializerHelper.EntityToJson(entity);

                    return PackJsonResult("true", s, string.Empty);


                }
                catch (Exception ex)
                {
                    return PackJsonResult("false", string.Empty, ex.Message);
                }
            }
        }

        /// <summary>
        /// 因为需要写入numer，所以override
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public override string SaveOrUpdate(string json)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                ITransaction tx = null;

                Organization entity = JsonSerializerHelper.JsonToEntity<Organization>(json);

                try
                {
                    tx = sess.BeginTransaction();
                    
                    if (entity.Parent == null)
                        entity.Number = "1";
                    else
                    {
                        var parent = sess.CreateQuery("from Organization o where o.Id=" + entity.Parent.Id).UniqueResult<Organization>();
                        

                        int maxNum = 0;
                        foreach (var item in parent.Childs)
                        {
                            int lastNumber = int.Parse(item.Number);// int.Parse(item.Number.Substring(item.Number.LastIndexOf('.') + 1));
                            if (maxNum < lastNumber)
                                maxNum = lastNumber;
                        }
                        //获取父节点的所有子节点的number的最大值，加1就是该节点的number
                        maxNum++;
                        entity.Number = maxNum.ToString();
                        entity.FullNumber = string.Format("{0}.{1}", parent.FullNumber, maxNum);
                    }
                    

                    sess.SaveOrUpdate(entity);
                    tx.Commit();
                    //有点sb了，凑合补救一下
                    //正确的做法是定义个包含Id的interface，所有要持久化的类都实现这个interface
                    dynamic d = entity;
                    return PackJsonResult("true", d.Id.ToString(), string.Empty);
                }
                catch (Exception ex)
                {
                    if (tx != null && tx.IsActive)
                        tx.Rollback();

                    return PackJsonResult("false", "0", ex.Message);
                }
            }
        }


        public string GetUserOrg(int userId)
        {
            using (ISession session = SessionFactory.Session)
            {
                
                var user = session.CreateQuery("from User u where u.Id = " + userId + " ").UniqueResult<User>();
                if (user != null || user.Role != null)
                {
                    //if (user.Role.Name != "分公司系统管理员")
                    //{
                    //    return this.PackJsonResult("true", JsonConvert.Null, string.Empty);
                    //}
                    //else
                    {
                        if (user.Organization != null)
                        {
                            var root = new Organization { Id = user.Organization.Id, Name = user.Organization.Name };
                            initChildren(session, root);

                            using (StringWriter sw = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
                            {
                                JsonSerializer serializer = new JsonSerializer
                                {
                                    NullValueHandling = NullValueHandling.Ignore,
                                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                };

                                using (JsonWriter jw = new JsonTextWriter(sw))
                                {
                                    jw.Formatting = Formatting.Indented;

                                    serializer.Serialize(jw, root);
                                }
                                return PackJsonResult("true", sw.ToString(), string.Empty);
                            }
                        }
                        else
                        {
                            return this.PackJsonResult("true", JsonConvert.Null, string.Empty);
                        }
                    }
                }
                else
                {
                    return this.PackJsonResult("true", JsonConvert.Null, string.Empty);
                }
            }
        }
    }
}
